package com.weilele.mvvm.utils.thread

import com.weilele.mvvm.mainHandler

/**
 * 自动循环任务
 */
class LoopTask(private val runnable: LoopTask.() -> Unit, private val time: Long) :
        Runnable {
    companion object {
        fun start(time: Long = 1000L, run: LoopTask.() -> Unit): LoopTask {
            return LoopTask(run, time).also {
                it.run()
            }
        }

        fun LoopTask.stop() {
            cancel()
        }
    }

    override fun run() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q
                && mainHandler.hasCallbacks(this)) {
            return
        }
        mainHandler.postDelayed(this, time)
        runnable.invoke(this)
    }

    fun cancel() {
        mainHandler.removeCallbacks(this)
    }
}
